package com.xiang.ad.index.adplan;

import com.xiang.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xiang.
 * adPlan的索引实现类，实现indexAware，实现对index的crud
 */
@Slf4j
@Component  //作为spring的组件存在
public class AdPlanIndex implements IndexAware<Long, AdPlanObject> {

    //使用map存储index
    private static Map<Long, AdPlanObject> objectMap;

    //初始化map，使用ConcurrentHashMap(由于服务在使用过程中会涉及到索引的更新，更新需要这个map是线程安全的)
    static {
        objectMap = new ConcurrentHashMap<>();
    }
    //==============================================================================================
    //根据key获取AdPlanObject
    @Override
    public AdPlanObject get(Long key) {
        return objectMap.get(key);
    }

    //添加索引，构建map
    @Override
    public void add(Long key, AdPlanObject value) {

        log.info("before add: {}", objectMap);
        objectMap.put(key, value);
        log.info("after add: {}", objectMap);//再次打印日志查看是否实现了索引的更新
    }

    //更新索引
    @Override
    public void update(Long key, AdPlanObject value) {

        log.info("before update: {}", objectMap);//记录更新前的内容

        AdPlanObject oldObject = objectMap.get(key);//根据key获取AdPlanObject
        if (null == oldObject) {//如果空，就添加
            objectMap.put(key, value);
        } else {//非空就添加
            oldObject.update(value);
        }

        log.info("after update: {}", objectMap);//查看更新结果
    }

    //删除索引
    @Override
    public void delete(Long key, AdPlanObject value) {

        log.info("before delete: {}", objectMap);
        objectMap.remove(key);
        log.info("after delete: {}", objectMap);//通过日志对比查看结果
    }
}
